package com.example.nutritionmanager.home

import android.annotation.SuppressLint
import android.graphics.Paint
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.cos
import kotlin.math.sin
import android.app.DatePickerDialog
import android.widget.DatePicker
import androidx.compose.foundation.Image
import androidx.compose.runtime.*
import androidx.compose.ui.res.painterResource
import androidx.hilt.navigation.compose.hiltViewModel
import java.util.*
import com.example.nutritionmanager.R
import com.example.nutritionmanager.viewModels.IntakeViewModel
import java.text.SimpleDateFormat

/*
  营养摄入仪表盘
  指针从正右方为0度，顺时针旋转
  仪表盘显示为201度到339度，共138度
  刻度为0%到120%，共7个，每1%为1.15度
 */
const val startAngle = 201f // 仪表盘起始角度
const val endAngle = 339f // 仪表盘结束角度
const val angleRange = endAngle - startAngle // 仪表盘旋转范围
@SuppressLint("DefaultLocale")
@Composable
fun IntakeDashboard(
    intakeViewModel: IntakeViewModel = hiltViewModel(),
    modifier: Modifier = Modifier
) {
    val colorScheme = MaterialTheme.colorScheme
    // 当前摄入量
    val currentIntake by intakeViewModel.currentCalorie.collectAsState()
    // 今日最大摄入量
    val maxIntake by intakeViewModel.maxCalorie.collectAsState()

    // 计算摄入量的比例 (0 到 1 之间)
    val intakeRatio = if (maxIntake > 0) currentIntake / maxIntake else 0f

    // 计算指针的旋转角度（根据比例），如果比例超过1.2，则指针指向结束角度，否则指向比例对应的角度，每1%为138 / 120 = 1.15度
    val pointerAngle = if (intakeRatio > 1.2f) endAngle else (intakeRatio * angleRange / 1.2f) + startAngle

    // 日期选择的逻辑
    var selectedDate by remember { mutableStateOf(getCurrentDate()) }
    var showDatePicker by remember { mutableStateOf(false) }

    // 前一天和后一天的逻辑
    val calendar = Calendar.getInstance()
    val (year, month, dayOfMonth) = selectedDate.split("-").map { it.toInt() }
    calendar.set(year, month - 1, dayOfMonth)
    // 处理前一天和后一天
    fun adjustDate(isPrevious: Boolean) {
        calendar.add(Calendar.DAY_OF_YEAR, if (isPrevious) -1 else 1)
        selectedDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.time)
    }

    if (showDatePicker) {
        DatePickerDialog(
            LocalContext.current,
            { _, year, month, dayOfMonth ->
                // 月份修正：DatePickerDialog 传入的月份是0基的，应该加1
                val formattedMonth = String.format("%02d", month + 1) // 月份补零
                val formattedDay = String.format("%02d", dayOfMonth)   // 日期补零
                selectedDate = "$year-$formattedMonth-$formattedDay"
//                selectedDate = "$year-${month + 1}-$dayOfMonth"
                showDatePicker = false
                intakeViewModel.updateDate(selectedDate)
            },
            year,
            month - 1,  // month 这里不加1
            dayOfMonth
        ).apply {
            setOnDismissListener { showDatePicker = false }
        }.show()
    }

    Text(
        text = "今日摄入",
        color = colorScheme.onBackground,
        fontSize = 16.sp,
        fontWeight = FontWeight.Bold,
        modifier = Modifier.padding(bottom = 8.dp)
    )
    // 卡路里仪表盘和添加餐食按钮，放入圆角矩形内
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(4.dp),
        colors = CardDefaults.cardColors(containerColor = colorScheme.surface)
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, end = 16.dp, top = 5.dp, bottom = 16.dp)
        ) {
            // 显示日期选择部分
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                // TODO:  /* 处理前一天的逻辑 */
                IconButton(onClick = {
                    adjustDate(true)
                    intakeViewModel.updateDate(selectedDate)
                }) {
                    Image(
                        painter = painterResource(id = R.drawable.left_arrow),
                        contentDescription = "Previous Day"
                    )
//                    Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Previous Day")
                }

                // 显示当前日期并点击弹出日历
                TextButton(onClick = { showDatePicker = true }) {
                    Text(text = selectedDate, fontSize = 16.sp, color = colorScheme.onSurface)
                }
                // TODO:  /* 处理后一天的逻辑 */
                IconButton(onClick = {
                    adjustDate(false)
                    intakeViewModel.updateDate(selectedDate)
                }) {
                    Image(
                        painter = painterResource(id = R.drawable.right_arrow),
                        contentDescription = "Previous Day"
                    )                }
            }
            // 饮食仪表盘
            Box(
                modifier = modifier
//            .border(1.dp, Color.Black)
                    .height(200.dp)
                    .width(300.dp)
//            .size(300.dp)  // 仪表盘的大小
                    .padding(start = 16.dp, end = 16.dp),
                contentAlignment = Alignment.Center
            ) {
                // 绘制仪表盘的底部圆
                Canvas(modifier = Modifier.fillMaxSize()) {
                    val radius = size.width * 0.49f
                    val center = Offset(size.width / 2, size.height * 0.9f)

                    // 底部圆形背景
                    drawArc(
                        color = Color(217, 217, 217, 80),
                        startAngle = startAngle,
                        sweepAngle = angleRange,
                        useCenter = false,
                        size = Size(radius * 2, radius * 2),
                        topLeft = Offset(center.x - radius, center.y - radius),
                        style = Stroke(width = size.width * 0.15f)
                    )
                }
                // 渐变背景颜色条
                Canvas(modifier = Modifier.fillMaxSize()) {
                    val width = size.width
                    val height = size.height
                    val radius = size.width / 2 + 10
                    val center = Offset(size.width / 2, size.height * 0.9f)

                    // 绘制渐变颜色条（圆弧）
                    val gradientBrush = Brush.linearGradient(
                        colors = listOf(Color.Green, Color.Yellow, Color.Red),
                        start = Offset(0f, 0f),
                        end = Offset(width, 0f)
                    )

                    drawArc(
                        brush = gradientBrush,
                        startAngle = startAngle,
                        sweepAngle = angleRange,  // 根据比例控制渐变的长度
                        useCenter = false,
                        size = Size(radius * 2, radius * 2),
                        topLeft = Offset(center.x - radius, center.y - radius),
                        style = Stroke(width = size.width * 0.04f)
                    )
                }

                // 绘制指针
                Canvas(modifier = Modifier.size(250.dp)) {
                    val radius = size.width / 2
                    val center = Offset(size.width / 2, size.height * 0.9f)
                    val pinAngle = 4f // 指针尖端角度的一半
                    val pointerLength = size.width * 0.3f

                    // 计算指针的角度(弧度制)
                    val angle = Math.toRadians(pointerAngle.toDouble()).toFloat()

                    val path = Path().apply {
                        moveTo(center.x + (radius - 20) * cos(angle).toFloat(), center.y + (radius - 20) * sin(angle).toFloat())
                        val deltaAngle1 = 270 - pinAngle - pointerAngle
                        val deltaAngle2 = 270 - pointerAngle
                        val deltaRadians1 = Math.toRadians(deltaAngle1.toDouble()).toFloat()
                        val deltaRadians2 = Math.toRadians(deltaAngle2.toDouble()).toFloat()
                        val pinAngleRadians = Math.toRadians(pinAngle.toDouble()).toFloat()

                        relativeLineTo(pointerLength * sin(deltaRadians1), pointerLength * cos(deltaRadians1))
                        relativeLineTo(pointerLength * 2 * sin(pinAngleRadians) * cos(deltaRadians2), -pointerLength * 2 * sin(pinAngleRadians) * sin(deltaRadians2))
                        close()
                    }

                    // 绘制三角形指针
                    drawPath(
                        path = path,
                        color = colorScheme.onSurface
                    )
                }

                // 显示摄入量百分比
                Text(
                    text = "${(intakeRatio * 100).toInt()}%",
                    color = colorScheme.onSurface,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .padding(bottom = 20.dp)
                )

                // 绘制刻度
                DrawScales()
            }

            Row (
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Column() {
                    Text(
                        text = "今日已摄入",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 8.dp, end = 100.dp)
                    )
                    Text(
                        text = "${currentIntake.toInt()} kcal",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier
                            .padding(bottom = 8.dp, end = 100.dp)
                            .align(Alignment.CenterHorizontally)
                    )
                }
                Column() {
                    Text(
                        text = "今日最大摄入",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    Text(
                        text = "${maxIntake.toInt()} kcal",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier
                            .padding(bottom = 8.dp)
                            .align(Alignment.CenterHorizontally)
                    )
                }
            }
        }
    }


}

@Composable
fun DrawScales() {
    Canvas(modifier = Modifier.fillMaxSize()) {
        val width = size.width
        val height = size.height
        val radius = size.width / 2
        val center = Offset(width / 2, size.height * 0.9f)

        // 设置刻度字体大小和颜色
        val scaleFontSize = 10.sp
        val scaleColor = Color.Gray

        for (i in 0..6) {
            val angle = Math.toRadians((angleRange * i / 6 + startAngle).toDouble()) // 刻度均匀分布在三分之一圆上
            val x = center.x + (radius - 35) * cos(angle).toFloat()
            val y = center.y + (radius - 35) * sin(angle).toFloat()

            // 绘制每个刻度的数字
            drawContext.canvas.nativeCanvas.apply {
                drawText(
                    "${(i * 20)}%",  // 刻度的数字
                    x, y,
                    Paint().apply {
                        color = scaleColor.toArgb()
                        textSize = scaleFontSize.toPx()
                        textAlign = Paint.Align.CENTER
                    }
                )
            }
        }
    }
}
fun getCurrentDate(): String {
    val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    return sdf.format(Date())
}
